<?php

namespace backend\widgets;


use backend\assets\DataRangePickerAsset;
use yii\base\Model;
use yii\grid\DataColumn;
use yii\helpers\Html;
use Yii;

class DatetimeColumn extends DataColumn
{
    public $relative = true;

    public $expire;

    public $format = 'datetime';

    public $empty;

    public $dateRangeOptions = [];

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if (!isset($this->expire)) {
            $this->expire = time() - 7 * 86400;
        }
    }

    /**
     * @inheritdoc
     */
    protected function renderDataCellContent($model, $key, $index)
    {
        if ($this->content === null) {
            $value = $this->getDataCellValue($model, $key, $index);

            if ($value) {
                $real = $this->grid->formatter->format($value, 'dateTime');
                if ($this->expire && $value > $this->expire && $this->relative) {
                    $value = $this->grid->formatter->format($value, 'relativeTime');
                } else {
                    $value = $this->grid->formatter->format($value, $this->format);
                }

                return '<abbr title="' . $real . '">' . $value  . "</abbr>";
            } else {
                return $this->empty ? $this->empty : $value;
            }
        } else {
            return parent::renderDataCellContent($model, $key, $index);
        }
    }

    /**
     * @inheritdoc
     */
    protected function renderFilterCellContent()
    {
        if (is_string($this->filter)) {
            return $this->filter;
        }

        $model = $this->grid->filterModel;

        if ($this->filter !== false && $model instanceof Model && $this->attribute !== null && $model->isAttributeActive($this->attribute)) {
            if ($model->hasErrors($this->attribute)) {
                Html::addCssClass($this->filterOptions, 'has-error');
                $error = Html::error($model, $this->attribute, $this->grid->filterErrorOptions);
            } else {
                $error = '';
            }
            $name = Html::getInputName($model, $this->attribute);
            $this->registerClientScript($name);
            if (is_array($this->filter)) {
                $options = array_merge(['prompt' => ''], $this->filterInputOptions);
                return Html::activeDropDownList($model, $this->attribute, $this->filter, $options) . ' ' . $error;
            } else {
                return Html::activeTextInput($model, $this->attribute, $this->filterInputOptions) . ' ' . $error;
            }
        } else {
            return parent::renderFilterCellContent();
        }
    }

    protected function registerClientScript($name)
    {
        $view = $this->grid->getView();
        DataRangePickerAsset::register($view);
        if (!isset($this->dateRangeOptions['ranges']) || $this->dateRangeOptions['ranges'] !== false) {
            $this->dateRangeOptions['ranges'] = [
                '今天' => [date('Y-m-d'), date('Y-m-d')],
                '昨天' => [date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime('yesterday'))],
                '最近7天' => [date('Y-m-d', strtotime('-7 days')), date('Y-m-d')],
                '最近30天' => [date('Y-m-d', strtotime('-30 days')), date('Y-m-d')],
                '这个月' => [date('Y-m-d', strtotime('first day of this month')), date('Y-m-d')],
                '上个月' => [date('Y-m-d', strtotime('first day of previous month')), date('Y-m-d', strtotime('last day of previous month'))],
            ];
        }
        $this->dateRangeOptions = array_merge([
            'separator' => ' / ',
            'format' => 'YYYY-MM-DD',
            'locale' => [
                'applyLabel' => '确定',
                'cancelLabel' => '取消',
                'fromLabel' => '从',
                'toLabel' => '至',
                'weekLabel' => '周',
                'customRangeLabel' => '自定义',
            ]
        ], $this->dateRangeOptions);
        $options = json_encode($this->dateRangeOptions, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $language = Yii::$app->language;
        $gridId = $this->grid->options['id'];
        $js = "moment.locale('{$language}'); $('[name=\"{$name}\"]').daterangepicker({$options}).on('apply.daterangepicker', function() {jQuery('#{$gridId}').yiiGridView('applyFilter');});";
        $view->registerJs($js);
    }
}